<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\ModelList;
use App\Models\ModelVersion;
use Illuminate\Support\Facades\Storage;

class ModelSuccess extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'model:success';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测模型是否训练完成';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::beginTransaction();
        //获取模型转换中数据
        $info = ModelVersion::where('status',5)->lockForUpdate()->first();
        if($info){
            $filePath = $info->train.'exp0/weights/file.zip';
            if(Storage::disk('modelTrain')->exists($filePath)){
                $newPath = 'train/'.$info->train.md5($info->train).'.zip';
                Storage::disk('admin')->put($newPath, Storage::disk('modelTrain')->get($filePath));

                //修改完成状态
                ModelVersion::where('id',$info->id)->update([
                    'status' => 2,
                    'train_file' => $newPath
                ]);

                ModelList::where('id',$info->model_id)->update([
                    'train_file' => $newPath,
                    'train_version' => $info['version']
                ]);
            }else{
                ModelVersion::where('id',$info->id)->update(['status'=>3]);
            }
        }

        DB::commit();
        return true;
    }
}
